package com.zbkj.front.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.servlet.ServletUtil;
import com.zbkj.common.constants.SmsConstants;
import com.zbkj.common.constants.SysConfigConstants;
import com.zbkj.common.constants.UserConstants;
import com.zbkj.common.dto.IpLocation;
import com.zbkj.common.exception.CrmebException;
import com.zbkj.common.model.user.User;
import com.zbkj.common.request.IosBindingPhoneRequest;
import com.zbkj.common.result.CommonResultCode;
import com.zbkj.common.token.FrontTokenComponent;
import com.zbkj.common.utils.*;
import com.zbkj.front.service.IosService;
import com.zbkj.service.service.SystemConfigService;
import com.zbkj.service.service.UserService;
import com.zbkj.service.service.UserTokenService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Pattern;
import java.util.Date;

/**
 * IOS服务实现类
 * +----------------------------------------------------------------------
 * | CRMEB [ CRMEB赋能开发者，助力企业发展 ]
 * +----------------------------------------------------------------------
 * | Copyright (c) 2016~2025 https://www.crmeb.com All rights reserved.
 * +----------------------------------------------------------------------
 * | Licensed CRMEB并不是自由软件，未经许可不能去掉CRMEB相关版权
 * +----------------------------------------------------------------------
 * | Author: CRMEB Team <admin@crmeb.com>
 * +----------------------------------------------------------------------
 */
@Service
public class IosServiceImpl implements IosService {

    private static final Logger logger = LoggerFactory.getLogger(IosServiceImpl.class);

    @Autowired
    private UserService userService;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private SystemConfigService systemConfigService;
    @Autowired
    private UserTokenService userTokenService;
    @Autowired
    private FrontTokenComponent tokenComponent;


    /**
     * ios绑定手机号（登录后）
     *
     * @param request 请求对象
     * @return 是否绑定
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String bindingPhone(IosBindingPhoneRequest request) {
        checkValidateCode(request.getPhone(), request.getCaptcha(), SmsConstants.VERIFICATION_CODE_SCENARIO_LOGIN);

        User tempUser = userService.getByPhone(request.getPhone());
        if (tempUser != null) {
            if (StrUtil.isNotBlank(tempUser.getAppleOpenid())) {
                throw new CrmebException(CommonResultCode.VALIDATE_FAILED, "手机号已被绑定");
            }
            tempUser.setAppleOpenid(request.getAppleOpenid());
            //更新uid
            userTokenService.updateUidByOpenid(tempUser.getId(), request.getAppleOpenid());
            userService.updateAppleOpenid(request.getPhone(), request.getAppleOpenid());
            String userToken = tokenComponent.createUserToken(tempUser);
            return userToken;
        } else {
            //注册用户
            String phone = request.getPhone();
            User user = new User();
            user.setAccount(phone);
            user.setPwd(CommonUtil.createPwd(phone));
            user.setPhone(phone);
            user.setRegisterType(UserConstants.REGISTER_TYPE_IOS);
            user.setNickname(CommonUtil.createNickName(phone));
            user.setAvatar(systemConfigService.getValueByKey(SysConfigConstants.USER_DEFAULT_AVATAR_CONFIG_KEY));
            Date nowDate = CrmebDateUtil.nowDateTime();
            user.setCreateTime(nowDate);
            user.setLastLoginTime(nowDate);
            user.setLevel(1);
            user.setAppleOpenid(request.getAppleOpenid());
            user.setIsBindingIos(true);

            try {
                HttpServletRequest httpServletRequest = RequestUtil.getRequest();
                String clientIP = ServletUtil.getClientIP(httpServletRequest, null);
                if (StrUtil.isBlank(clientIP)) {
                    logger.error("获取用户ip失败，用户phone = " + user.getPhone());
                } else {
                    IpLocation ipLocation = IPUtil.getLocation(clientIP);
                    if (ObjectUtil.isNotNull(ipLocation.getCountry())) {
                        user.setCountry(ipLocation.getCountry().equals("中国") ? "CN" : "OTHER");
                        user.setProvince(ipLocation.getProvince());
                        user.setCity(ipLocation.getCity());
                    }
                }
            } catch (Exception e) {
                logger.error("通过ip获取用户位置失败，用户phone = {}", user.getPhone());
                logger.error("通过ip获取用户位置失败", e);
            }
            userService.save(user);
            //更新uid
            userTokenService.updateUidByOpenid(user.getId(), request.getAppleOpenid());
            String userToken = tokenComponent.createUserToken(user);
            return userToken;

        }
//        if (ObjectUtil.isNotNull(tempUser)) {
//            throw new CrmebException(CommonResultCode.VALIDATE_FAILED, "手机号已注册");
//        }

        // 可以绑定
//        Integer userId = userService.getUserIdException();
//        User user = userService.getById(userId);
//        user.setPhone(request.getPhone());
//        user.setPwd(CommonUtil.createPwd(request.getPhone()));
//        user.setAccount(request.getPhone());
//        return userService.updateById(user);
    }

    /**
     * 检测手机验证码
     *
     * @param phone 手机号
     * @param code  验证码
     */
    private void checkValidateCode(String phone, String code, String login) {
        Object validateCode = redisUtil.get(StrUtil.format(SmsConstants.SMS_VERIFICATION_CODE_PHONE, login, phone));
        if (validateCode == null) {
            throw new CrmebException(CommonResultCode.VALIDATE_FAILED, "验证码已过期");
        }
        if (!validateCode.toString().equals(code)) {
            throw new CrmebException(CommonResultCode.VALIDATE_FAILED, "验证码错误");
        }
        //删除验证码
        redisUtil.delete(StrUtil.format(SmsConstants.SMS_VERIFICATION_CODE_PHONE, login, phone));
    }

}
